package com.greenhouse9.prog07;

import java.io.*;
import java.net.*;
import java.util.Properties;
import java.util.HashMap;
import java.util.Iterator;


public class UrlFactory
{

    private String url;

    UrlFactory (String host, String path, HashMap<String, String> hm) {

        StringBuilder sb = new StringBuilder ();

        sb.append("http://" + host);
        sb.append(path);

        short i = 0;

        Iterator<String> it = hm.keySet().iterator();

        try {

            while(it.hasNext()) {

                String key = (String)it.next();
                if (hm.get(key) != null && hm.get(key).length() != 0) {
                    if (i==0){ sb.append("?");}
                    else { sb.append("&");}
                    sb.append(key + "=" + URLEncoder.encode(hm.get(key),"UTF8"));
                    i++;
                }
            }
        } catch (Exception e) {
            System.err.println(e);
        }

        url = sb.toString();

    }

    public String getUrl (){
        return url;
    }


    public static void main(String[] args)
    {
	if ( args.length != 2 ){
	    System.err.println("�R�}���h���C����� URL �Əo�͐�t�@�C�������w�肵�Ă�������");
	    return;
	}

	// �ڑ���� URL
    String strUrl;

	// �o�͐�̃t�@�C����
	String file = args[1];

    StringBuilder sbUrl = new StringBuilder ();

    // property file name
    Properties prop = new Properties ();
    try{
        prop.load( new FileInputStream("url.properties") );

        System.out.println("host: " + prop.getProperty("host"));
        System.out.println("path: " + prop.getProperty("path"));
    }
    catch (IOException e) {
        System.err.println( e );
    }

	try{
	    if ( (new File(file)).exists() ){
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		System.err.println("*** " + file + " �͊�ɑ��݂��܂��D");
		System.err.print("�㏑�����܂����H ([y]/n) > ");
		String answer = br.readLine();
		br.close();
		if ( !answer.equals("y") && !answer.equals("yes") &&
		     answer.length() != 0 ){
		    System.err.println("���f���܂��D");
		    return;
		}
	    }

        URI uri = new URI("http://www.amazon.co.jp/���傢�f�L-���t�V��-��-�c�v/dp/4166605917/");
	    //System.err.println("Path: " + uri.getPath());
        //System.err.println("String: " + uri.toString());
        //System.err.println("AString: " + uri.toASCIIString());

        URI uri2 = uri.normalize();
	    //System.err.println("---- uri2 ----");
	    //System.err.println("Path: " + uri2.getPath());
        //System.err.println("String: " + uri2.toString());
        //System.err.println("AString: " + uri2.toASCIIString());

        sbUrl.append("http://");
        sbUrl.append(prop.getProperty("host"));
        sbUrl.append(prop.getProperty("path"));
        sbUrl.append("?appid=");
        sbUrl.append(prop.getProperty("appid"));
        sbUrl.append("&query=");
        sbUrl.append(URLEncoder.encode("�F�c�j�q", "UTF8"));

        //url
        System.out.println("sb: " + sbUrl.toString());

        strUrl = sbUrl.toString();
        //strUrl = URLEncoder.encode(sbUrl.toString(), "UTF8");

        //url
        System.out.println("Url enc: " + strUrl);

        URI uri3 = new URI("http://shopping.yahooapis.jp/ShoppingWebService/V1/itemSearch?appid=" + "&query=�哇�D�q");
	    System.err.println("---- uri3 ----");
	    System.err.println("Path: " + uri3.getPath());
        System.err.println("String: " + uri3.toString());
        System.err.println("AString: " + uri3.toASCIIString());

	    URL url = new URL(strUrl);
	    //url =uri3.toURL();
        System.out.println(url.toString());

        int x = doProcess(url, new FileOutputStream(file));

	}
	catch( IOException e ){
	    System.err.println("���s");
	    System.err.println( e );
	}
    catch( Exception e ) {
	    System.err.println("���s");
	    System.err.println( e );
    }
    }

    private static int doProcess(URL url, OutputStream os){
        // URL ����W���G���[�o�͂ɏo��
        System.err.println("�y�v���g�R���z " + url.getProtocol());
        System.err.println("�y �z �X �g �z " + url.getHost());
        System.err.println("�y �t�@�C�� �z " + url.getFile());
        System.err.print("�y�|�[�g�ԍ��z ");
        if( url.getPort() == -1 )
            System.err.println( url.getDefaultPort() );
        else System.err.println( url.getPort() );

        try {

            // HTTP �ڑ��I�u�W�F�N�g�̎擾
            HttpURLConnection http = (HttpURLConnection)url.openConnection();

            // GET ���\�b�h�ɐݒ�
            http.setRequestMethod("GET");

            // �ڑ�
            System.err.print("�ڑ��� ... ");
            http.connect();
            System.err.println("����");
            // �R���e���c�̎擾�ƕۑ�
            System.err.print("�R���e���c�擾�� ... ");
            BufferedInputStream bis
                = new BufferedInputStream( http.getInputStream() );
            int data;
            BufferedOutputStream bos
                = new BufferedOutputStream( os );
            while ( (data = bis.read()) != -1 ){
                bos.write(data);
            }
            bos.close();
            System.err.println("�I��");

            // �����R�[�h�����b�Z�[�W
            System.err.println("�y�����R�[�h�z " + http.getResponseCode()
               + " " + http.getResponseMessage() );

        } catch ( IOException e ) {
            System.err.println("���s");
            System.err.println( e );
        }

        return 0;
    }
}
